/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package mysqlviewer.model;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
import mysqlviewer.gui.DialogPesan;

/**
 *
 * @author agoesh
 */
public class ModelTabel extends AbstractTableModel{
    private Object[][] isiTabel;
    private String[] judulTabel;
    
    public ModelTabel(Connection c, String namaDB, String namaTB){
        buatTabel(c, namaDB, namaTB);
    }
    
    public void buatTabel(Connection c, String namaDB, String namaTB){
        try{
            Statement state=c.createStatement();
            state.executeQuery("USE "+namaDB);
            ResultSet hasil=state.executeQuery("SELECT * FROM "+namaTB);
            
            ResultSetMetaData meta=hasil.getMetaData();
            judulTabel=new String[meta.getColumnCount()];
            for(int i=0;i<meta.getColumnCount();i++){
                judulTabel[i]=meta.getColumnName(i+1);
            }
            
            //masukan Isi Tabel kedalam variabel Object[][] isiTabel
            hasil.last();
            isiTabel=new Object[hasil.getRow()][judulTabel.length];
            int j=0;
            hasil.beforeFirst();
            while(hasil.next()){
                for(int i=0;i<judulTabel.length;i++){
                    isiTabel[j][i]=hasil.getString(i+1);
                }
                j++;
            }
        }catch(Exception e){
            new DialogPesan(null, true, e.getMessage());
        }
    }
    
    public int getRowCount() {
        return isiTabel.length;
    }

    public int getColumnCount() {
        return judulTabel.length;
    }

    public Object getValueAt(int rowIndex, int columnIndex) {
        return isiTabel[rowIndex][columnIndex];
    }
    
    @Override
    public String getColumnName(int index){
        return judulTabel[index];
    }
}
